package br.cn.evo.controller;

import java.io.IOException;

import br.cn.evo.model.Solution;
import br.cn.evo.util.Formulas;
import br.cn.evo.util.IO;
import br.cn.evo.util.EnumTypes.AdaptativeStep;
import br.cn.evo.util.EnumTypes.Function;
import br.cn.evo.util.EnumTypes.Result;
import br.cn.evo.util.EnumTypes.SelectionType;

public class Th implements Runnable{
	
	AdaptativeStep q;
	
	public Th(AdaptativeStep q) {
		super();
		this.q = q;
	}

	public void doThread(AdaptativeStep q){
		Function function = Function.Fuel;
		AdaptativeStep adp = q;
		Result local = Result.LocalMinimum;
		SelectionType sel = SelectionType.Elitism;

		int populationSize = 1000;
		int numberParametersSolution = 16;
		int numberIteractions = 10000;
		int maxPopulation = 1000;
		int numberGroup = maxPopulation/10;

		int media = 30;
		double[] arrayMedia = new double[numberIteractions];
		Solution[] arraySol = new Solution[media];
		
		

		for (int i = 0; i < media; i++) {
			double[] arrayAct =  new double[numberIteractions];			

			arrayAct = EvolutionaryProgramming.doEvolutionaryProgramming(function, local, adp, sel, numberParametersSolution, populationSize, 
					numberIteractions, maxPopulation, numberGroup);

			arraySol[i] = EvolutionaryProgramming.bestSol;

			try {
				IO.writeFile(q.name()+"_total_airplane_"+i+".txt", arrayAct);
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}

			for (int j = 0; j < arrayAct.length; j++) {
				double arM = arrayAct[j]/media;
				arrayMedia[j] += arM; 
			}
			
			
			EvolutionaryProgramming.min = Double.MAX_VALUE;
			EvolutionaryProgramming.max = Double.MIN_VALUE;
			System.out.println("qqq");
		}
		
		int mediaPassageiros = 0;
		for (int i = 0; i < arraySol.length; i++) {
			mediaPassageiros  += arraySol[i].getPassageiros();
		}
		mediaPassageiros = mediaPassageiros/media;
		/*
		for (int i = 0; i < arrayMedia.length; i++) {
			arrayMedia[i] = arrayMedia[i]/media;
		}
		*/
		double tempo = Formulas.TIME(arraySol[0].getArrayValues()[0], 0, arraySol[0].getArrayValues()[2]);
		System.out.println("Tempo : "+tempo);
		System.out.println("Distancia : "+Formulas.MUV(0, 0, arraySol[0].getArrayValues()[2], tempo));

		System.out.println("DIST: "+Fitness.distancex);
		try {
			IO.writeFile(q.name()+"_media_total_airplane.txt", arrayMedia);
			IO.writeFile(q.name()+"_param_total.txt", arraySol, mediaPassageiros);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	@Override
	public void run() {
		doThread(q);
	}


}
